# -*- coding: utf-8 -*-
# created on 2017/04/14
from sympy import solveset
from mathsolver.functions.base import BaseFunction, BaseNumber, BaseSymbolValue, new_latex
from mathsolver.functions.hanshu.helper import yizhizhiyu_qiufanwei


class FenDuanHanShuFangCheng(BaseFunction):
    """解分段函数方程"""

    def solver(self, *args):
        piecefunc, func = args
        func_var, func_expr = func.var, func.expression
        canshu = func_var.free_symbols.pop()

        canshu_quzhi = []
        for piece_expr, inter in piecefunc.expression:
            # 求属于某个区间时，参数满足的条件
            canshu_fanwei = yizhizhiyu_qiufanwei(func_var, inter)
            self.steps.append(["", "当 %s ∈ %s 时：" % (new_latex(func_var), new_latex(inter))])

            # 解方程
            canshu_solver = solveset(piece_expr.subs(piecefunc.var, func_var) - func_expr, domain=canshu_fanwei)
            self.steps.append(["", "将 %s 代入 %s 解方程：" % (new_latex(func_var), new_latex(piece_expr))])

            if canshu_solver:
                canshu_quzhi.extend(canshu_solver)
                self.steps.append(["", "得 %s = %s " % (new_latex(canshu), canshu_solver)])
            else:
                self.steps.append(["", "方程无解"])

        self.output.append(BaseSymbolValue({canshu: canshu_quzhi}))
        self.label.add("解分段函数方程")
        return self


class FenDuanHanShuQiuCan(BaseFunction):
    """分段函数值求参数"""

    def solver(self, *args):
        piecefunc, func, funcname = args
        func_var, func_expr = func.var, func.expression
        canshu = func_var.free_symbols.pop()

        canshu_quzhi = []
        for piece_expr, inter in piecefunc.expression:
            # 求属于某个区间时，参数满足的条件
            canshu_fanwei = yizhizhiyu_qiufanwei(func_var, inter)
            self.steps.append(["", "当 %s ∈ %s 时：" % (new_latex(func_var), new_latex(inter))])

            # 解方程
            canshu_solver = solveset(piece_expr.subs(piecefunc.var, func_var) - func_expr, domain=canshu_fanwei)
            self.steps.append(["", "将 %s 代入 %s 解方程：" % (new_latex(func_var), new_latex(piece_expr))])

            if canshu_solver:
                canshu_quzhi.extend(canshu_solver)
                self.steps.append(["", "得 %s = %s " % (new_latex(canshu), canshu_solver)])
            else:
                self.steps.append(["", "方程无解"])

        for canshu_value in canshu_quzhi:
            funcname_value = funcname.var.subs(canshu, canshu_value)
            result = piecefunc.run(funcname_value)
            self.steps.append(["", "所以 %s = %s" % (funcname.printing(), result)])
            self.output.append(BaseNumber(result))

        self.label.add("分段函数值求参数")
        return self


if __name__ == '__main__':
    pass
